{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a102e471",
   "metadata": {},
   "source": [
    "# Trade-Policy Dynamics: Evidence from 60 Years of U.S.-China Trade\n",
    "Alessandria,  Khan, Khederlarian, Ruhl, and Steinberg\n",
    "\n",
    "**inputs:**   ecm_robustness1_lr.tex</br> \n",
    "&emsp; &emsp; &emsp;ecm_robustness1.tex</br>\n",
    "&emsp; &emsp; &emsp;ecm_robustness2_lr.tex</br>\n",
    "&emsp; &emsp; &emsp;ecm_robustness2.tex</br>\n",
    "&emsp; &emsp; &emsp;nntr_PS.tex</br>\n",
    "&emsp; &emsp; &emsp;annualtsusa_robustness.tex</br>\n",
    "&emsp; &emsp; &emsp;annualhs8_robustness.tex</br>\n",
    "&emsp; &emsp; &emsp;nntr_robustness1.tex</br>\n",
    "\n",
    "**outputs:** </br> \n",
    "&emsp; &emsp; &ensp; &ensp;  tableG3.tex</br>\n",
    "&emsp; &emsp; &ensp; &ensp;  tableG4.tex</br>\n",
    "&emsp; &emsp; &ensp; &ensp;  tableG5.tex</br>\n",
    "&emsp; &emsp; &ensp; &ensp;  tableG6.tex</br>\n",
    "&emsp; &emsp; &ensp; &ensp;  tableG7.tex</br>\n",
    "&emsp; &emsp; &ensp; &ensp;  tableG8.tex</br>\n",
    "&emsp; &emsp; &ensp; &ensp;  tableG9.tex</br>\n",
    "\n",
    "This code creates the tables in the appendix. \n",
    "\n",
    "Table G1 is created in `12 Code final outputs/10 tables.ipynb` as some numbers in it are cited in the article. </br>\n",
    "Table G2 is coded directly in the manuscript as the concordance is from the literature.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "fee2d2d0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "dir_eint = '../20 Intermediate files/'\n",
    "dir_out = '../31 Final output files appendix/'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "24ee2303",
   "metadata": {},
   "outputs": [],
   "source": [
    "def make_row(x):\n",
    "    return '&'.join(x) + '\\\\\\\\'\n",
    "\n",
    "def insert_name(x, name):\n",
    "    x = x.split('&')\n",
    "    x[0] = name\n",
    "    return '&'.join(x)\n",
    "\n",
    "def insert_names(tl, names):\n",
    "    for k in names:\n",
    "        tl[k] = insert_name(tl[k],names[k])\n",
    "    return tl\n",
    "\n",
    "def text_to_num(l):\n",
    "    l = l.split('&')\n",
    "    return [float(e.strip()[:5]) for e in l[1:]]\n",
    "\n",
    "def load_stata_tabstar(fname, colspec, width):\n",
    "    with open(fname, 'r') as f:\n",
    "        t = f.readlines()\n",
    "    t = t[2:-4] + [t[-2]]\n",
    "    t = [r.strip() for r in t]\n",
    "    t[0] = '\\\\begin{tabular*}{' + str(width) + '\\\\textwidth}{' + colspec + '}'\n",
    "    t[-1] = '\\\\end{tabular*}'\n",
    "    return t\n",
    "    \n",
    "def write_latex(fname, t):\n",
    "    with open(fname, 'w') as f:\n",
    "        f.write('\\n'.join(t))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c32e51a4",
   "metadata": {},
   "source": [
    "# Table G3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "bea5c0fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load the long-run estimates. Extract the numeric data. \n",
    "with open(dir_eint+'ecm_robustness1_lr.tex', 'r') as f:\n",
    "    g3lr_l = f.readlines()\n",
    "g3lr_l = [r.strip() for r in g3lr_l[6:11]]\n",
    "\n",
    "lrcn = text_to_num(g3lr_l[0])\n",
    "lron = text_to_num(g3lr_l[3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "14c62dd2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load the remaining estimates. \n",
    "g3_l = load_stata_tabstar(dir_eint+'ecm_robustness1.tex', 'l@{\\\\extracolsep{\\\\fill}}cccccc',1)\n",
    "\n",
    "header = [' ', 'Baseline', 'Shipping', 'All Goods', 'All Countries', 'Full', 'Balanced']\n",
    "fes = ['FE']+['$gt,jt,gj$']*6\n",
    "g3_l[2] = make_row(header)\n",
    "g3_l.insert(-4, make_row(fes))\n",
    "\n",
    "# Fix the variable names\n",
    "names = {7:'$\\mathbbm{1}\\\\{j=China\\\\}\\\\Delta\\\\tau_{jgt}$', \n",
    "         19:'$\\mathbbm{1}\\\\{j=China\\\\}\\\\tau_{jg,t-1}$',\n",
    "         13:'$\\mathbbm{1}\\\\{j=China\\\\} v_{jg,t-1}$', \n",
    "         4:'$\\mathbbm{1}\\\\{j \\\\ne China\\\\}\\\\Delta\\\\tau_{jgt}$',\n",
    "         16:'$\\mathbbm{1}\\\\{j \\\\ne China\\\\}\\\\tau_{jg,t-1}$', \n",
    "         10:'$\\mathbbm{1}\\\\{j \\\\ne China\\\\} v_{jg,t-1}$',\n",
    "         22: 'Shipping Costs$_{jgt}$', \n",
    "         27:'Adjusted R$^2$'}\n",
    "g3_l = insert_names(g3_l, names)\n",
    "\n",
    "# Insert the long-run elasticities \n",
    "g3_l = g3_l[:25] + g3lr_l + ['\\\\addlinespace'] + g3_l[25:]\n",
    "\n",
    "# Extract the short-run elasticities\n",
    "srcn = text_to_num(g3_l[4])\n",
    "sron = text_to_num(g3_l[7])\n",
    "\n",
    "# Compute the ratios of long to short elasticities\n",
    "ratioc, ratioo = [], []\n",
    "for i in range(0,6):\n",
    "    ratioc.append( str(round(lrcn[i]/srcn[i],2)))\n",
    "    ratioo.append(str(round(lron[i]/sron[i],2)))\n",
    "\n",
    "# Add them to the table, rename\n",
    "g3_l.insert(-5, make_row([' ']+ratioc))\n",
    "g3_l.insert(-5, '\\\\addlinespace')\n",
    "g3_l.insert(-5, make_row([' ']+ratioo))\n",
    "g3_l.insert(-5, '\\\\midrule')\n",
    "names = {-7:'Long-/Short-run Others', -9:'Long-/Short-run China', -12:'Lon-run Others', -15:'Long-run China'}\n",
    "g3_l = insert_names(g3_l, names)\n",
    "\n",
    "#print('\\n'.join(g3_l))\n",
    "write_latex(dir_out+'tableG3.tex', g3_l)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06fa3e71",
   "metadata": {},
   "source": [
    "# Table G4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load the long-run estimates. Extract the numeric data. \n",
    "with open(dir_eint+'ecm_robustness2_lr.tex', 'r') as f:\n",
    "    g4lr_l = f.readlines()\n",
    "g4lr_l = [r.strip() for r in g4lr_l[6:11]]\n",
    "\n",
    "lrcn = text_to_num(g4lr_l[0])\n",
    "lron = text_to_num(g4lr_l[3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "cfa81004",
   "metadata": {},
   "outputs": [],
   "source": [
    "g4_l = load_stata_tabstar(dir_eint+'ecm_robustness2.tex', 'l@{\\\\extracolsep{\\\\fill}}ccccc',0.85)\n",
    "\n",
    "# Header and FEs\n",
    "header = [' ', 'SITC', 'TSUSA', 'SITC', 'HS-8', 'SITC']\n",
    "fes = ['FE']+['$gt,jt,gj$']*5\n",
    "g4_l[2] = make_row(header)\n",
    "g4_l.insert(-4, make_row(fes))\n",
    "g4_l.insert(2, ' &\\\\multicolumn{1}{c}{1974--2008} &\\\\multicolumn{2}{c}{1974--1988} &\\\\multicolumn{2}{c}{1989--2008}\\\\\\\\')\n",
    "g4_l.insert(3, ' \\\\cmidrule(lr){2-2} \\\\cmidrule(lr){3-4} \\\\cmidrule(lr){5-6} ')\n",
    "\n",
    "# Fix the variable names\n",
    "names = {9:'$\\mathbbm{1}\\\\{j=China\\\\}\\\\Delta\\\\tau_{jgt}$', \n",
    "         21:'$\\mathbbm{1}\\\\{j=China\\\\}\\\\tau_{jg,t-1}$',\n",
    "         15:'$\\mathbbm{1}\\\\{j=China\\\\} v_{jg,t-1}$', \n",
    "         6:'$\\mathbbm{1}\\\\{j \\\\ne China\\\\}\\\\Delta\\\\tau_{jgt}$',\n",
    "         18:'$\\mathbbm{1}\\\\{j \\\\ne China\\\\}\\\\tau_{jg,t-1}$', \n",
    "         12:'$\\mathbbm{1}\\\\{j \\\\ne China\\\\} v_{jg,t-1}$',\n",
    "         24: 'Shipping Costs$_{jgt}$', \n",
    "         -3:'Adjusted R$^2$'}\n",
    "g4_l = insert_names(g4_l, names)\n",
    "\n",
    "# Insert the long-run elasticities \n",
    "g4_l = g4_l[:27] + g4lr_l + ['\\\\addlinespace'] + g4_l[27:]\n",
    "\n",
    "# Extract the short-run elasticities\n",
    "srcn = text_to_num(g4_l[6])\n",
    "sron = text_to_num(g4_l[9])\n",
    "\n",
    "# Compute the ratios of long to short elasticities\n",
    "ratioc, ratioo = [], []\n",
    "for i in range(0,5):\n",
    "    ratioc.append( str(round(lrcn[i]/srcn[i],2)))\n",
    "    ratioo.append(str(round(lron[i]/sron[i],2)))\n",
    "\n",
    "# Add them to the table, rename\n",
    "g4_l.insert(-5, make_row([' ']+ratioc))\n",
    "g4_l.insert(-5, '\\\\addlinespace')\n",
    "g4_l.insert(-5, make_row([' ']+ratioo))\n",
    "g4_l.insert(-5, '\\\\midrule')\n",
    "names = {-7:'Long-/Short-run Others', -9:'Long-/Short-run China', -12:'Lon-run Others', -15:'Long-run China'}\n",
    "g4_l = insert_names(g4_l, names)\n",
    "\n",
    "# print('\\n'.join(g4_l))\n",
    "write_latex(dir_out+'tableG4.tex', g4_l)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0aa08079",
   "metadata": {},
   "source": [
    "# Table G5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "201a58c8",
   "metadata": {},
   "outputs": [],
   "source": [
    "g5_l = load_stata_tabstar(dir_eint+'nntr_PS.tex', 'l@{\\\\extracolsep{\\\\fill}}cccccc', 1)\n",
    "\n",
    "# Fix the header\n",
    "g5_l[2] = '& \\\\multicolumn{2}{c}{NTR Gap} &\\\\multicolumn{2}{c}{Statutory NNTR} &\\\\multicolumn{2}{c}{Applied NNTR} \\\\\\\\'\n",
    "\n",
    "# Fix the variable names\n",
    "names = {4:'$\\mathbbm{1} \\\\{\\\\substack{ {t>2000} \\\\\\\\ {j=China} }\\\\}  NTR Gap_{g}$',\n",
    "        7:'$\\\\tau_{jgt}$',\n",
    "        10:'$\\mathbbm{1} \\\\{\\\\substack{ {t>2000} \\\\\\\\ {j=China} }\\\\}  NNTR$',\n",
    "        13:'$\\mathbbm{1} \\\\{\\\\substack{ {t>2000} \\\\\\\\ {j=China} }\\\\}  AppNNTR{g}$',\n",
    "        -3:'Adjusted R$^2$'}\n",
    "g5_l = insert_names(g5_l, names)\n",
    "\n",
    "# Move the tariff lines to the bottom\n",
    "temp = g5_l[7:10]\n",
    "del g5_l[7:10]\n",
    "g5_l.insert(12, temp[2])\n",
    "g5_l.insert(13, temp[0])\n",
    "g5_l.insert(14, temp[1])\n",
    "\n",
    "# Add row of fixed effects\n",
    "fes = ['FE']+['$gt,jt,gj$']*6\n",
    "g5_l.insert(-4, make_row(fes))\n",
    "\n",
    "# Add row of periods\n",
    "pds = [\"Period\",\"'92--'07\", \"'74--'08\", \"'92--'07\", \"'74--'08\", \"'92--'07\", \"'74--'08\"]\n",
    "g5_l.insert(-5, make_row(pds))\n",
    "\n",
    "# print('\\n'.join(g5_l))\n",
    "write_latex(dir_out+'tableG5.tex', g5_l)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3699ae6",
   "metadata": {},
   "source": [
    "# Table G6"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "e7d3153d",
   "metadata": {},
   "outputs": [],
   "source": [
    "g6_l = load_stata_tabstar(dir_eint+'annualtsusa_robustness.tex', 'l@{\\\\extracolsep{\\\\fill}}cccc', 0.77)\n",
    "\n",
    "# Fix header\n",
    "g6_l[2] = make_row([' ',  'Baseline', 'All Countries', 'Avg.\\\\ NNTR, 1974--79', 'Tariffs'])\n",
    "\n",
    "# Remove extra space & the standard errors\n",
    "g6_l = [i for i in g6_l if (i != '\\\\addlinespace') and (i[0] != '&')]\n",
    "\n",
    "# Add row of fixed effects\n",
    "fes = ['FE']+['$gt,jt,gj$']*4 \n",
    "g6_l.insert(-4, make_row(fes))\n",
    "\n",
    "# Fix names\n",
    "names = {k:str(v) for (k,v) in zip(range(4,19), range(1974,1989))}\n",
    "names[-3] = 'Adjusted R$^2$'\n",
    "names[-7] = '$\\\\tau_{jgt}$'\n",
    "g8_l = insert_names(g6_l, names)\n",
    "\n",
    "# Add variable name\n",
    "g6_l.insert(4, \"$\\mathbbm{1} \\\\{\\\\substack{ {t=t'} \\\\\\\\ {j=China} }\\\\}  X_{g}$ &&&&\\\\\\\\\")\n",
    "\n",
    "# Drop 2008 and time varying nuisance parameter\n",
    "del g6_l[-8]\n",
    "\n",
    "# print('\\n'.join(g6_l))\n",
    "write_latex(dir_out+'tableG6.tex', g6_l)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b5c84f4e",
   "metadata": {},
   "source": [
    "# Table G7"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "52d319df",
   "metadata": {},
   "outputs": [],
   "source": [
    "g7_l = load_stata_tabstar(dir_eint+'annualhs8_robustness.tex', 'l@{\\\\extracolsep{\\\\fill}}ccccc', 0.77)\n",
    "\n",
    "# Fix header\n",
    "g7_l[2] = make_row([' ',  'Baseline', 'No Tariffs', 'All Countries', 'Full', 'Balanced'])\n",
    "\n",
    "# Remove extra space & the standard errors\n",
    "g7_l = [i for i in g7_l if (i != '\\\\addlinespace') and (i[0] != '&')]\n",
    "\n",
    "# Add row of fixed effects\n",
    "fes = ['FE']+['$gt,jt,gj$']*5 \n",
    "g7_l.insert(-4, make_row(fes))\n",
    "\n",
    "# Fix names\n",
    "names = {k:str(v) for (k,v) in zip(range(4,24), range(1989,2009))}\n",
    "names[-3] = 'Adjusted R$^2$'\n",
    "names[-7] = '$\\\\tau_{jgt}$'\n",
    "g7_l = insert_names(g7_l, names)\n",
    "\n",
    "# Add variable name\n",
    "g7_l.insert(4, \"$\\mathbbm{1} \\\\{\\\\substack{ {t=t'} \\\\\\\\ {j=China} }\\\\}  X_{g}$ &&&&\\\\\\\\\")\n",
    "\n",
    "# Drop 2008 and time varying nuisance parameter\n",
    "del g7_l[-8]\n",
    "\n",
    "# print('\\n'.join(g7_l))\n",
    "write_latex(dir_out+'tableG7.tex', g7_l)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9a1c193c",
   "metadata": {},
   "source": [
    "# Table G8"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "7695222e",
   "metadata": {},
   "outputs": [],
   "source": [
    "g8_l = load_stata_tabstar(dir_eint+'nntr_robustness1.tex', 'l@{\\\\extracolsep{\\\\fill}}ccccc', 1)\n",
    "\n",
    "# Fix the header\n",
    "g8_l[2] = make_row([' ',  'Baseline', 'All Countries', 'Full', 'Balanced', 'Only U.S.-China'])\n",
    "\n",
    "# Remove extra space & the standard errors\n",
    "g8_l = [i for i in g8_l if (i != '\\\\addlinespace') and (i[0] != '&')]\n",
    "# g8_l = [i for i in g8_l if (i[0] != '&')]\n",
    "\n",
    "# Add row of fixed effects\n",
    "fes = ['FE']+['$gt,jt,gj$']*4 + ['$jt,gj$']\n",
    "g8_l.insert(-4, make_row(fes))\n",
    "\n",
    "# Fix names\n",
    "names = {k:str(v) for (k,v) in zip(range(4,39), range(1974,2009))}\n",
    "names[-3] = 'Adjusted R$^2$'\n",
    "g8_l = insert_names(g8_l, names)\n",
    "\n",
    "# Add variable name\n",
    "g8_l.insert(4, \"$\\mathbbm{1} \\\\{\\\\substack{ {t=t'} \\\\\\\\ {j=China} }\\\\}  X_{g}$ &&&&&\\\\\\\\\")\n",
    "\n",
    "# Drop 2008 and time varying nuisance parameter\n",
    "del g8_l[-7]\n",
    "\n",
    "# print('\\n'.join(g8_l))\n",
    "write_latex(dir_out+'tableG8.tex', g8_l)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "701592c4",
   "metadata": {},
   "source": [
    "# Table G9"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "a57a295e",
   "metadata": {},
   "outputs": [],
   "source": [
    "g9_l = load_stata_tabstar(dir_eint+'nntr_robustness2.tex', 'l@{\\\\extracolsep{\\\\fill}}cccccc', 1)\n",
    "\n",
    "# Fix the header\n",
    "g9_l[2] = make_row([' ',  'NNTR', 'Applied', 'Time-Varying', 'Shipping', 'Tariffs', 'Anticipation'])\n",
    "g9_l.insert(2, \" &\\\\multicolumn{3}{c}{Alternative gap measures}&\\\\multicolumn{2}{c}{Other trade costs}&\\\\\\\\\")\n",
    "g9_l.insert(3,'\\\\cmidrule(lr){2-4} \\\\cmidrule(lr){5-6}')\n",
    "\n",
    "# Remove extra space & the standard errors\n",
    "g9_l = [i for i in g9_l if (i != '\\\\addlinespace')]\n",
    "g9_l = [i for i in g9_l if (i[0] != '&')]\n",
    "\n",
    "# Drop 2008 and time varying nuisance parameter\n",
    "del g9_l[-9]\n",
    "del g9_l[-9]\n",
    "\n",
    "# Fix names\n",
    "names = {k:str(v) for (k,v) in zip(range(6,40), range(1974,2008))}\n",
    "names[-3] = 'Adjusted R$^2$'\n",
    "names[-8] = 'log Shipping Cost$_{jgt}$'\n",
    "names[-7] = '$\\\\tau_{jgt}$'\n",
    "names[-6] = '$\\\\Delta\\\\tau_{jg,t+1}$'\n",
    "g9_l = insert_names(g9_l, names)\n",
    "\n",
    "# Add row of fixed effects\n",
    "fes = ['FE']+['$gt,jt,gj$']*6 \n",
    "g9_l.insert(-4, make_row(fes))\n",
    "\n",
    "# Add variable name\n",
    "g9_l.insert(6, \"$\\mathbbm{1} \\\\{\\\\substack{ {t=t'} \\\\\\\\ {j=China} }\\\\}  X_{g}$ &&&&&\\\\\\\\\")\n",
    "\n",
    "# print('\\n'.join(g9_l))\n",
    "write_latex(dir_out+'tableG9.tex', g9_l)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "808ea429",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "newest",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.19"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
